<script setup>
import { ref, watchEffect } from 'vue';
import { ElMessage } from 'element-plus';
import { createBed, fetchBedDetail } from '@/api/bed'; // Assuming fetchBedDetail is available
import { Check, Close } from '@element-plus/icons-vue';

// --- Props and Emits ---
const props = defineProps({
    mode: {
        type: String,
        required: true,
        validator: (value) => ['add', 'view'].includes(value),
    },
    bedId: {
        type: Number,
        default: null,
    },
});

const emit = defineEmits(['close']);

// --- Component State ---
const formRef = ref(null);
const loading = ref(false);
const dialogVisible = ref(true);

const form = ref({
    bedNumber: '',
    roomNumber: '',
    costPerMonth: 0,
    notes: '',
});

const formRules = {
    bedNumber: [{ required: true, message: '请输入床位号', trigger: 'blur' }],
    roomNumber: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
    costPerMonth: [{ required: true, message: '请输入月费用', trigger: 'blur' }],
};

// --- Logic ---
const title = props.mode === 'add' ? '新增床位' : '床位详情';

// **REACTIVITY FIX**: Use watchEffect to handle prop changes correctly.
watchEffect(async () => {
    if (props.mode === 'view' && props.bedId) {
        loading.value = true;
        try {
            const data = await fetchBedDetail(props.bedId);
            form.value = { ...data };
        } catch (error) {
            ElMessage.error('获取床位详情失败');
            console.error(error);
            handleCancel(); // Close modal if data fetch fails
        } finally {
            loading.value = false;
        }
    } else {
        // Reset form for 'add' mode
        form.value = { bedNumber: '', roomNumber: '', costPerMonth: 0, notes: '' };
    }
});

const handleSubmit = async () => {
    if (props.mode === 'view') {
        handleCancel();
        return;
    }

    await formRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true;
            try {
                await createBed(form.value);
                ElMessage.success('新增床位成功！');
                emit('close', true); // Pass true to indicate a refresh is needed
            } catch (error) {
                ElMessage.error('新增床位失败');
                console.error(error);
            } finally {
                loading.value = false;
            }
        }
    });
};

const handleCancel = () => {
    dialogVisible.value = false;
    // The @close event on el-dialog will trigger the parent's handler
};

const onDialogClose = () => {
    emit('close', false); // Always emit close event
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="35%"
    :close-on-click-modal="false"
    @close="onDialogClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="mode === 'add' ? formRules : {}"
      label-width="100px"
      v-loading="loading"
      class="bed-form"
    >
      <el-form-item label="房间号" prop="roomNumber">
        <el-input
          v-model="form.roomNumber"
          :disabled="mode === 'view'"
          placeholder="例如：301"
        />
      </el-form-item>
      <el-form-item label="床位号" prop="bedNumber">
        <el-input
          v-model="form.bedNumber"
          :disabled="mode === 'view'"
          placeholder="例如：A01"
        />
      </el-form-item>
      <el-form-item label="月费用" prop="costPerMonth">
        <el-input-number
          v-model="form.costPerMonth"
          :disabled="mode === 'view'"
          :min="0"
          :precision="2"
          controls-position="right"
          placeholder="请输入月费用"
          class="full-width"
        />
      </el-form-item>
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="form.notes"
          :disabled="mode === 'view'"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息（可选）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button :icon="Close" @click="handleCancel">
          {{ mode === 'add' ? '取消' : '关闭' }}
        </el-button>
        <el-button v-if="mode === 'add'" type="primary" :icon="Check" @click="handleSubmit" :loading="loading">
          确定新增
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.bed-form {
  padding: 0 20px;
}
.full-width {
  width: 100%;
}
</style>